<?php

/**
 *	  资金流向：流出
 *    收入类型：卖家同意退款
 *
 *    @author   psmb
 *    @usage    none
 */
class RefundOutlay extends OutlayDepopay
{
    var $_purpose_name = 'refund';
	
	
	function submit($data)
	{
		/* 释放trade_info和extra_info和post三个变量 */
        extract($data);
        /* 处理交易基本信息 */
        $base_info = $this->_handle_trade_info($trade_info, $post, $this->_purpose_name);
		
        if (!$base_info)
        {
            /* 基本信息验证不通过 */
            return false;
        }
		
		$tradesn = $this->_gen_trade_sn();
		
		/* 插入收支记录，并变更账户余额 */
		if(!$this->_insert_record_info($tradesn, $trade_info, $extra_info, $post)) {
			return false;
		}
		
		/* 修改退款状态，并增加退款日志 */
		if(!$this->_update_refund_status($tradesn, $trade_info, $extra_info, $post)) {
			$this->_errorCode[] = "50007";
			return false;
		}
		/* 退款成功后，处理订单状态 */
		if(!$this->_handle_order_status($tradesn, $trade_info, $extra_info)) {
			return false;
		}
		
		return $tradesn;
	}
	
	/* 插入收支记录，并变更账户余额 */
	function _insert_record_info($tradesn, $trade_info, $extra_info, $post)
	{
		$refund_mod = &m('refund');
		$refund = $refund_mod->get($extra_info['refund_id']);
		
		$order_id = $extra_info['order_id'];

		$intro = $this->_get_intro_by_order($order_id);

		
		// 退款给买家
		$time = gmtime();
		$data_record = array(
			'tradesn'	=>	$tradesn,
			'order_sn'	=>	$extra_info['order_sn'],
			'user_id'	=>	$trade_info['party_id'], // 买家
			'party_id'	=>	0,
			'amount'	=>	$trade_info['amount'],
			'balance'	=>	$this->_get_deposit_balance($trade_info['party_id']) + $trade_info['amount'], // 增加后的余额
			'flow'		=>	'income',
			'purpose'	=>	$this->_purpose_name,
			'status'	=>	'SUCCESS',
			'payway'	=>	LANG::get('deposit'),
			'name'		=>	LANG::get('refundin') . ' - ' . $intro,
			'remark'	=>	'',
			'add_time'	=>	$time,
			'pay_time'	=>	$time,
			'end_time'  =>  $time,
		);
		$step1 = parent::_insert_deposit_record($data_record);
		
		if($step1)
		{
			/* 如果不是全额（单个退款商品，含分摊运费）退款，则需要把退款差价打给卖家 */
			$chajia = $refund['total_fee'] - $trade_info['amount'];
			if($chajia > 0)
			{
				$time = gmtime();
				$data_record = array(
					'tradesn'	=>	$tradesn,
					'order_sn'	=>	$extra_info['order_sn'],
					'user_id'	=>	$trade_info['user_id'], // 卖家
					'party_id'	=>	0,
					'amount'	=>	$chajia,
					'balance'	=>	$this->_get_deposit_balance($trade_info['user_id']) + $chajia, // 增加后的余额
					'flow'		=>	'income',
					'purpose'	=>	'refunddiff', // 退款差价
					'status'	=>	'SUCCESS',
					'payway'	=>	LANG::get('deposit'),
					'name'		=>	LANG::get('refunddiff') . ' - ' . $intro,
					'remark'	=>	'',
					'add_time'	=>	$time,
					'pay_time'	=>	$time,
					'end_time'  =>  $time,
				);
				$step2 = parent::_insert_deposit_record($data_record);
			}
		}
		else
		{
			$this->_errorCode[] = "50006";
			return false;
		}
		return true;
	}
	
	/* 修改退款状态，并增加退款日志 */
	function _update_refund_status($tradesn, $trade_info, $extra_info, $post)
	{
		$refund_id = $extra_info['refund_id'];
		$refund_mod = &m('refund');
		$refund_message_mod = &m('refund_message');
		
		$refund_mod->edit($refund_id, array('status'=>'SUCCESS', 'end_time' => gmtime()));
		
		// 判断是平台客服处理退款，还是卖家同意退款
		if(isset($extra_info['operator']) && $extra_info['operator'] == 'admin') {
			$content = sprintf(Lang::get('admin_agree_refund_content_change'),Lang::get('system_customer'), $post['refund_goods_fee'], $post['refund_shipping_fee'], $post['content']);
			
			// 如果是平台客服处理退款，还需要更新退款金额和退运费金额
			$refund_shipping_fee = $post['refund_shipping_fee'] ? $post['refund_shipping_fee'] : 0;
			$refund_mod->edit($refund_id, array('refund_goods_fee'=>$post['refund_goods_fee'], 'refund_shipping_fee'=>$refund_shipping_fee, 'ask_customer'=>1));
			
		} else $content = sprintf(Lang::get('seller_agree_refund_content_change'), $extra_info['seller_name']);
		
		/* 增加退款日志 */
		$data = array(
			'owner_id'	=> $extra_info['seller_id'],
			'owner_role'=> 'seller',
			'refund_id'	=> $refund_id,
			'content'	=> $content,
			'created'	=> gmtime()				
		);
		return $refund_message_mod->add($data);
	}
	
	/* 退款成功过后，修改订单状态，并插入订单变更日志 */
	function _handle_order_status($tradesn, $trade_info, $extra_info)
	{
		$order_mod = &m('order');
		$order_log_mod = &m('orderlog');
		$refund_id = $extra_info['refund_id'];
		

		if(!$order_mod->edit($extra_info['order_id'], array('status' => ORDER_CANCELED, 'finished_time' => gmtime()))){

			$this->_errorCode[] = "50013";

			return false;

		}
		
		// 修改买家收支记录状态为已完成
		$deposit_record_mod = &m('deposit_record');
		$deposit_record_mod->edit('flow ="outlay" AND user_id='.$extra_info['buyer_id'] . ' AND party_id='.$extra_info['seller_id'] . ' AND order_sn=' . $extra_info['order_sn'], array('status' => 'SUCCESS', 'end_time' => gmtime()));
		

		// 判断是管理员处理退款，还是卖家同意退款

		if(isset($extra_info['operator']) && $extra_info['operator'] == 'admin') {

			$remark = Lang::get('admin_agree_refund_order_status_change');

		} else $remark = Lang::get('seller_agree_refund_order_status_change');

		/* 记录订单操作日志 */

		$data = array(
			'order_id'  		=> $extra_info['order_id'],
			'operator'  		=> 0,
			'order_status' 		=> order_status($extra_info['status']),
			'changed_status' 	=> order_status(ORDER_CANCELED),
			'remark'    		=> $remark,
			'log_time'  		=> gmtime(),
        );

		if(!$order_log_mod->add($data)) {

			$this->_errorCode[] = "50014";

			return false;

		}
		return true;
	}
	

	function _get_intro_by_order($order_id)
	{

		$intro = '';

		if(!$order_id) return $intro;

		$ordergoods_mod  = &m('ordergoods');

		$ordergoods = $ordergoods_mod->find(array('conditions'=>'order_id='.$order_id,'fields'=>'goods_name'));

		$ext = '';
		if($ordergoods) {
			if(count($ordergoods) > 1) {
				$ext = Lang::get('and_more');
			}
			$ordergoods = current($ordergoods);
			$intro = $ordergoods['goods_name'] . $ext;
		}

		return $intro;
	}
	
}

?>
